var eq_url = '/main/eq_ls/?q=';
var p = 0;
var q_old = '';
var has_next = true;
function loadXMLDoc() {
    var q_new = '';
    q_new = document.getElementById('equipment_search').value;
    if (q_new) {
        var eq_url_q = eq_url + q_new;
        if (q_new == q_old) {
            p += 1;
            if (p > 1){
                eq_url_q += "&page=" + p;
            };
        } else {
            has_next = true;
            p = 0;
        };
        q_old = q_new;
    } else {
        var eq_url_q = eq_url;
        p += 1;
        if (p >= 1){
            eq_url_q += "&page=" + p;
        };
    }

	var xmhttp = new XMLHttpRequest();
	xmhttp.onreadystatechange=function(){
		if (this.readyState==4 && this.status==200){
			makeSelect(this, q_new);
		}
	};
	xmhttp.open("GET",eq_url_q,true);
	xmhttp.send();
}
function makeSelect(jData, q_new) {
  var i;
  var obj = JSON.parse(jData.responseText);
  var d = obj.data;
  if (has_next && d) {
      if (p >= 1){
          var table="<option value='' selected>----Search by " + q_new + " (" + p + ")----</option>";
      } else{
          var table="<option value='' selected>----Search by " + q_new + "----</option>";
      }

      for (i = 0; i <d.length; i++) {
        table += "<option value='" + d[i].pk + "'> [" + d[i].pk + "] " + " (" + d[i].equipment_code + ") "
        + d[i].equipment_cn + "</option>";
      }
      document.getElementById("id_equipment").innerHTML += table;
  }
  has_next = obj.has_next;
  if (!has_next){
      document.getElementById('search_btn').className = 'btn btn-default';
  }
}

function refreshBtn() {
    document.getElementById('search_btn').className = 'btn btn-primary';
}

document.onkeydown = keyListener;
function keyListener(e) {
   if(e.keyCode == 13) {
       loadXMLDoc();
   }
}